package org.springframework.samples.petclinic.web

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.SessionAttributes
import org.springframework.web.bind.annotation.InitBinder
import org.springframework.web.bind.support.SessionStatus
import org.springframework.web.bind.WebDataBinder

import org.springframework.samples.petclinic.Clinic
import org.springframework.samples.petclinic.Owner
import org.springframework.samples.petclinic.validation.OwnerValidator

@Controller
@RequestMapping(Array("/editOwner.do"))
@SessionAttributes {val types = Array(classOf[Owner])}
class EditOwnerForm {

  private var clinic:Clinic = null

  @Autowired 
  def setClinic(clinic:Clinic) = {
    this.clinic = clinic
  }

  @InitBinder
  def setAllowedFields(dataBinder:WebDataBinder) = {
    dataBinder.setDisallowedFields(Array("id"))
  }
   
  @RequestMapping {val method = Array(RequestMethod.GET)}
  def setupForm(@RequestParam("ownerId") ownerId:Int, model:Model):String = {
    val owner = this.clinic.loadOwner(ownerId)
    model.addAttribute(owner)
    return "ownerForm"
  }
  
  @RequestMapping {val method = Array(RequestMethod.POST)}
  def processSubmit(@ModelAttribute owner:Owner, result:BindingResult, status:SessionStatus):String = {
    new OwnerValidator().validate(owner, result)
    if (result.hasErrors()) {
      return "ownerForm"
    } else {
      this.clinic.storeOwner(owner)
      status.setComplete()
      return "redirect:owner.do?ownerId=" + owner.id
    }
  }
}
